import React, { FC, memo, ReactNode, useEffect, useState } from 'react'
import { useLocation } from 'react-router-dom'

import { myShallowEqual, useMySelector } from '@/store'
import { getClassifyCascadeList } from '@/service/module/main/classify/question'
import {
  Button,
  Cascader,
  Checkbox,
  Col,
  Form,
  Input,
  message,
  Radio,
  Rate,
  Row,
  Space
} from 'antd'
import { MinusCircleOutlined } from '@ant-design/icons'
import { RadioChangeEvent } from 'antd/es/radio/interface'
import InfoTags from '@/views/main/c-views/question-manage/question-info/c-cpns/info-tags'
import { reqAddOrEditQuestion } from '@/service/module/main/question/question-info'

interface IProps {
  children?: ReactNode
}

const alphabetList = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
const options = [
  { optionName: 'A', optionValue: '' },
  { optionName: 'B', optionValue: '' },
  { optionName: 'C', optionValue: '' },
  { optionName: 'D', optionValue: '' }
]
const initialValues = {
  questionParse: options,
  questionOptions: options
}

const QUESTION_OPTIONS = 'questionOptions'
const QUESTION_PARSE = 'questionParse'

const QuestionInfo: FC<IProps> = (props) => {
  const { state = {} } = useLocation()
  const { currentRecord } = useMySelector(
    (state) => ({
      currentRecord: state.pageCommon.currentRecord
    }),
    myShallowEqual
  )

  const [cascadeList, setCascadeList] = useState<any[]>([])
  const [tags, setTags] = useState<string[]>([])
  const [questionType, setQuestionType] = useState(0)
  const [codeFlag, setCodeFlag] = useState(0)
  const [answerOptions, setAnswerOptions] = useState<string[]>([
    'A',
    'B',
    'C',
    'D'
  ])
  const [isAdd, setIsAdd] = useState(true)
  const [form] = Form.useForm()

  // 页面加载时做的操作
  useEffect(() => {
    const getCascadeList = async () => {
      const res = await getClassifyCascadeList()
      setCascadeList(res.data)
    }
    // 获取级联数据
    getCascadeList()
    console.log(currentRecord)
    // 编辑回显
    const isAdd = !state?.isEdit || !Object.keys(currentRecord).length
    setIsAdd(isAdd)
    if (isAdd) return
    const {
      questionTag,
      questionScore,
      questionParse,
      questionAnswer,
      questionCode,
      questionOptions,
      questionType,
      codeFlag,
      questionTitle,
      classifyFirstId,
      classifySecondId,
      classifyThirdId
    } = currentRecord
    setTags(questionTag)
    setCodeFlag(codeFlag)
    setQuestionType(questionType)
    form.setFieldsValue({
      questionScore,
      questionParse,
      questionAnswer: questionType === 1 ? questionAnswer : questionAnswer[0],
      questionOptions,
      code: questionCode?.code,
      codeFlag,
      questionType,
      questionTitle,
      classifyOptions: [classifyFirstId, classifySecondId, classifyThirdId]
    })
    console.log(form.getFieldsValue())
  }, [])

  const onFinish = async (values: any) => {
    const { classifyOptions, questionAnswer, code, ...newValues } = values
    const [classifyFirstId, classifySecondId, classifyThirdId] = classifyOptions
    const params = {
      ...newValues,
      questionAnswer: questionType === 1 ? questionAnswer : [questionAnswer],
      classifyFirstId,
      classifySecondId,
      classifyThirdId,
      questionTag: tags,
      questionCode: { code },
      ...(!isAdd && { questionId: currentRecord.questionId })
    }
    await reqAddOrEditQuestion(isAdd, params)
    // 恢复初始状态
    form.resetFields()
    setTags([])
    setAnswerOptions(['A', 'B', 'C', 'D'])
  }

  // 子传父：更新tags
  const updateTags = (tags: string[]) => {
    setTags(tags)
  }
  const onQuestionTypeChange = (e: RadioChangeEvent) => {
    // 更新题目类型状态
    const type = e.target.value
    setQuestionType(type)
    // 获取原数据
    const { questionOptions, questionParse } = form.getFieldsValue()
    // 如果不等于2（不等于判断题）就需要至少保留4个选项，判断题要截剩下两个选项
    const len = questionOptions.length
    if (type !== 2 && len >= 4) return
    // ****************** 对选项列表 ************************
    const getOptions = (key: string) => {
      const list = key === QUESTION_OPTIONS ? questionOptions : questionParse
      return type === 2 ? list.slice(0, 2) : [...list, ...options.slice(len, 4)]
    }
    const getQuestionOptions = getOptions(QUESTION_OPTIONS)
    form.setFieldsValue({
      questionOptions: getQuestionOptions,
      questionParse: getOptions(QUESTION_PARSE)
    })
    // ******************* 答案选择框 *************************
    const answers = getQuestionOptions.map((item: any) => item.optionName)
    setAnswerOptions(answers)
  }

  const addNewOption = () => {
    // *********************** 选项列表 ***************************
    // 获取选项列表原来的数据
    const { questionOptions, questionParse } = form.getFieldsValue()
    // 如果大于A,B,C,D,E,F,G这个字母列表数据，就退出，不允许增加 || 判断题已经做了处理了，一切换判断题就已经是最大选项了
    const newIndex = questionOptions.length
    if (!alphabetList[newIndex] || questionType === 2) {
      message.info('已经到了最大选项数~')
      return
    }
    // 要增加的选项数据
    const option = { optionName: alphabetList[newIndex], optionValue: '' }
    // 合并到原来的数据里面
    questionOptions.push(option)
    questionParse.push(option)
    // 更新表单数据
    form.setFieldsValue({
      questionOptions: questionOptions,
      questionParse: questionParse
    })
    // *********************** 答案选项 ***************************
    const answers = questionOptions.map((item: any) => item.optionName)
    setAnswerOptions(answers)
  }

  const removeOption = (key: number) => {
    // *********************** 选项列表 ***************************
    const questionOptions = form.getFieldValue(QUESTION_OPTIONS)
    const questionParse = form.getFieldValue(QUESTION_PARSE)
    // 这里只要一个的判断就行了，因为他们选项都是同步增加或者删除的
    if (!questionParse || !questionParse.length) return
    if (questionParse.length === 2) {
      message.warning('至少有两个选项哦~')
      return
    }
    // 删除对应的item项数据
    questionOptions.splice(key, 1)
    questionParse.splice(key, 1)
    // 重新整理表单数据
    const getOptions = (key: string) => {
      const list = key === QUESTION_OPTIONS ? questionOptions : questionParse
      return list.map((item: any, index: number) => ({
        optionName: alphabetList[index],
        optionValue: item.optionValue
      }))
    }
    // 更新表单数据
    const getQuestionOptions = getOptions(QUESTION_OPTIONS)
    form.setFieldValue(QUESTION_OPTIONS, getQuestionOptions)
    form.setFieldValue(QUESTION_PARSE, getOptions(QUESTION_PARSE))
    // *********************** 答案选择项 ***************************
    const answers = getQuestionOptions.map((item: any) => item.optionName)
    setAnswerOptions(answers)
  }
  return (
    <div>
      <Form
        form={form}
        size="small"
        initialValues={initialValues}
        name="question-info-add-or-edit"
        onFinish={onFinish}
        style={{ maxWidth: 800 }}
      >
        <Row>
          <Col span={12}>
            <Form.Item
              label="选择分类"
              name="classifyOptions"
              rules={[{ required: true }]}
            >
              <Cascader
                style={{ width: '250px' }}
                options={cascadeList}
                size="small"
                placeholder="请选择分类"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="选择题型"
              name="questionType"
              rules={[{ required: true }]}
            >
              <Radio.Group value={questionType} onChange={onQuestionTypeChange}>
                <Radio value={0}>单选题</Radio>
                <Radio value={1}>多选题</Radio>
                <Radio value={2}>判断题</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
        </Row>
        <Form.Item
          label="题目"
          name="questionTitle"
          rules={[{ required: true }]}
        >
          <Input placeholder="请输入题目" />
        </Form.Item>
        <Form.Item label="题目是否包含代码" name="codeFlag">
          <Radio.Group
            value={codeFlag}
            onChange={(e) => setCodeFlag(e.target.value)}
          >
            <Radio value={0}>否</Radio>
            <Radio value={1}>是</Radio>
          </Radio.Group>
        </Form.Item>
        {codeFlag === 1 && (
          <Form.Item name="code">
            <Input.TextArea style={{ width: '60%' }} rows={9} />
          </Form.Item>
        )}
        <Form.List name="questionOptions">
          {(fields) => (
            <>
              {fields.map(({ key, name, ...restField }) => (
                <Space
                  key={key}
                  style={{ display: 'flex', width: 700 }}
                  align="baseline"
                >
                  <Space.Compact size="small" style={{ width: 450 }}>
                    <Form.Item {...restField} name={[name, 'optionName']}>
                      <Input disabled style={{ width: '30px' }} />
                    </Form.Item>
                    <Form.Item
                      style={{ width: '100%' }}
                      {...restField}
                      name={[name, 'optionValue']}
                    >
                      <Input placeholder="请输入选项内容" />
                    </Form.Item>
                  </Space.Compact>
                  <MinusCircleOutlined onClick={() => removeOption(key)} />
                </Space>
              ))}
            </>
          )}
        </Form.List>
        <Form.Item
          label="题目答案"
          name="questionAnswer"
          rules={[{ required: true, message: '请选择答案' }]}
        >
          {questionType === 1 ? (
            <Checkbox.Group options={answerOptions}></Checkbox.Group>
          ) : (
            <Radio.Group options={answerOptions}></Radio.Group>
          )}
        </Form.Item>
        <Form.List name="questionParse">
          {(fields) => (
            <>
              {fields.map(({ key, name, ...restField }) => (
                <Space
                  key={key}
                  style={{ display: 'flex', width: 700 }}
                  align="baseline"
                >
                  <Space.Compact size="small" style={{ width: 450 }}>
                    <Form.Item {...restField} name={[name, 'optionName']}>
                      <Input disabled style={{ width: '30px' }} />
                    </Form.Item>
                    <Form.Item
                      style={{ width: '100%' }}
                      {...restField}
                      name={[name, 'optionValue']}
                    >
                      <Input placeholder="请输入选项解析" />
                    </Form.Item>
                  </Space.Compact>
                </Space>
              ))}
            </>
          )}
        </Form.List>
        <Row align="middle">
          <Col span={8}>
            <Form.Item label="题目难度" name="questionScore">
              <Rate style={{ fontSize: 16 }} allowHalf />
            </Form.Item>
          </Col>
          <Col span={16}>
            <Form.Item label="题目标签" name="questionTag">
              <InfoTags updateTags={updateTags} tags={tags} />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item>
          <Space>
            <Button
              style={{ padding: '0 20px' }}
              type="primary"
              htmlType="submit"
            >
              提交
            </Button>
            <Button
              style={{ padding: '0 20px' }}
              type="primary"
              onClick={addNewOption}
            >
              新增选项
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  )
}

export default memo(QuestionInfo)
